<template>
  <div v-loading="loading" element-loading-text="加载中。。。">
    <el-row :gutter="10" center class="monitor">
      <el-col :span="4">物理位置监控</el-col>
      <el-col :span="6" :offset="4">金科大厦-14楼</el-col>
      <el-col :span="10">
        <el-row>
          <!--  :disabled="" -->
          <el-button size="mini" type="primary" :disabled="!btnFlag" @click="canvasInit(0)">区域一：南区</el-button>
          <el-button size="mini" type="primary" :disabled="!btnFlag" @click="canvasInit(1)">区域二：北区</el-button>
          <!-- <el-button size="mini" @click="statusChange">南区本地数据请求</el-button> -->
          <!-- <el-button size="mini" @click="statusChange2">后台数据请求</el-button> -->
          <!-- <el-button size="mini" @click="queryOneSeat('002')">测试弹窗(AEENTID:002)</el-button> -->
        </el-row>
      </el-col>
    </el-row>
    <el-card style="margin-top:10px;height:1800px;">
      <el-container>
        <el-header height="30px" class="physical_title"></el-header>
        <el-container>
          <el-aside class="physical_left" width="1500px" height="613px">
            <el-col>
              <div>
                <canvas id="canvas" width="1300px" height="813px" style="border:1px solid black"></canvas>
              </div>
            </el-col>
       
            <el-col>

              <el-row >
                <el-col :span="8">
                  <label for="form" class="asideText">职场统计</label>
                  <el-form
                    :model="workPlaceStatistics"
                    ref="workPlaceStatistics"
                    size="mini"
                    label-position="left"
                    label-width="130px"
                  >
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="就绪座位数:" prop="WaitForNextCall">
                          <span class="itemText">{{workPlaceStatistics.WaitForNextCall}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="振铃座位数:" prop="CallRinging">
                          <span class="itemText">{{workPlaceStatistics.CallRinging}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="示忙座位数:" prop="NotReadyForNextCall">
                          <span class="itemText">{{workPlaceStatistics.NotReadyForNextCall}}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="话后小结座位数:" prop="AfterCallWork">
                          <span class="itemText">{{workPlaceStatistics.AfterCallWork}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="保持座位数:" prop="CallOnHold">
                          <span class="itemText">{{workPlaceStatistics.CallOnHold}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="未知通话座位数:" prop="CallUnknown">
                          <span class="itemText">{{workPlaceStatistics.CallUnknown}}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="咨询座位数:" prop="CallConsult">
                          <span class="itemText">{{workPlaceStatistics.CallConsult}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="内部通话座位数:" prop="CallInternal">
                          <span class="itemText">{{workPlaceStatistics.CallInternal}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="呼出座位数:" prop="CallOutbound">
                          <span class="itemText">{{workPlaceStatistics.CallOutbound}}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item label="呼入座位数:" prop="CallInbound">
                          <span class="itemText">{{workPlaceStatistics.CallInbound}}</span>
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item label="签出座位数:" prop="LoggedOut">
                          <span class="itemText">{{workPlaceStatistics.LoggedOut}}</span>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </el-col>
                <el-col :span="14" :offset="2">
                  <el-table
                    :data="tableData"
                    ref="table"
                    border
                    max-height="300"
                    :header-cell-style="{width:'20px',color:'#409EFF'}"
                  >
                    <el-table-column type="index" width="40"></el-table-column>
                    <el-table-column prop="WARNINFO" :label="tableLabel"></el-table-column>
                  </el-table>
                </el-col>
               <el-col>
                    <el-col><label class="asideText">备注说明</label></el-col>
                    <img src="static/images/image/show.png" width="890px" height="333px"  alt="备注说明图">
               </el-col>


              </el-row>
            </el-col>
          </el-aside>
        </el-container>
      </el-container>
    </el-card>
    <keep-alive>
      <component :is="dialogList.seatIforDialog" :option="dialogOptions"></component>
    </keep-alive>
  </div>
</template>
<script>
import toolBox from "@/common/utils/toolBox";
import seatIforDialog from "./dialog/seatIforDialog";
import request from "@/common/utils/request";
import getGlobalParams from "@/common/utils/getGlobalParams";
import query from "@/message/siteManagement/workplacemonitoring/query";
import subscribe from "@/message/paramManagement/realTimeParamSetting/subscribe";
import requestYg from "@/common/utils/requestYg";
import seatStatus from "@/message/siteManagement/workplacemonitoring/querySeatStatus";
import { fabric } from "fabric";
// 本地储存资源
import { statusList } from "./dataInfo";
// 98个工位 南区 本地模拟数据
import { seatList } from "./dataInfo";
// 初始化 地图 区域号 传参
import { areaInfo } from "./dataInfo";
import { constants } from "crypto";
export default {
  name: "",
  data() {
    return {
      // 后端可能会传的数据
      canvasObj: {},
      statusGroup: {},
      // 传值
      innitInfoData: {},
      AREANO: "1",
      backgroundURL: "",
      timer: null,
      btnFlag: true,
      // 弹窗相关
      currentRow: [],
      // currentRow: [{AGENTID:"坐席工号",AGENTNAME:"坐席名",YY_STATUS_CurrentAgentStatus:"当前状态",YY_CurrentAgentStatus_Time:"持续时间",loginIntime:"签入时间",EXTENSIONNO:"分机号",avecalltimes:"人均日化量",YY_TIME_CALLS_AVER:"通话均长",YY_TIME_CALLS_TOTAL:"通话时长",YY_TIME_AfterCallWork_AVER:"整理均长",YY_TIME_NotReady:"示忙时长",YY_TIME_AgentReady:"示闲时长",YY_TIME_AgentLogin:"值机时长",YY_NUM_NotReady:"示闲次数",availability:"工作时利用率"}], //表格当前选中行
      loading: false, //loading遮罩
      isDisabledDel: false,
      dialogList: {
        //指定被渲染组件列表
        seatIforDialog
      },
      dialogOptions: {
        //新增
        isShow: false
      },
      dialogOptions: { isShow: false, currentRow: [] },
      //  职场统计
      workPlaceStatistics: {
        WaitForNextCall: null, //'就绪'
        CallRinging: null, //'振玲'
        NotReadyForNextCall: null, //示忙
        AfterCallWork: null, //话后小结
        CallOnHold: null, //'保持'
        CallUnknown: null, //'未知通话'
        CallConsult: null, //'咨询'
        CallInternal: null, //'内部通话'
        CallOutbound: null, //'呼出'
        CallInbound: null, //'呼入'
        LoggedOut: null //'签出'
      },
      // 预警
      tableData: [],

      tableLabel: null
    };
  },
  computed: {},
  created: function() {},
  watch: {},
  mounted() {
    this.canvasInit();
  },

  methods: {
    getImageInfo(seat) {
      var imageInfos = statusList.filter(ele => {
        return ele.STATUS === seat.STATUS;
      });
      return imageInfos[0];
    },
    statusChange2() {
      let self = this;
      let resBody = new query();
    
      resBody.data.AREANO = this.AREANO;

      var resTimebefore = new Date().getTime();
      // console.log(
      //   "发送resBody.data,",
      //   resBody.data,
      //   "发送的时刻,",
      //   resTimebefore
      // );

      requestYg(resBody)
        .then(response => {
          var resTimeafter = new Date().getTime();
          // console.log(
          //   "后端返回的结果response,",
          //   response,
          //   "反映的时刻,",
          //   resTimeafter
          // );

          console.log(
            "发送开始-反映的时间-间隔，",
            resTimeafter - resTimebefore
          );

          if (response.SYS_HEAD.ReturnCode === "000000") {
            // 处理地图数据
            var resultData = response.RSP_BODY.struct || {};
            console.log("struct：", resultData);
            var count = 0;
            resultData.forEach(function(seat, index) {
              var imageInfo = self.getImageInfo(seat);

              self.statusGroup.forEachObject(function(seatGroup, index) {
                if (seatGroup.SEATNO === seat.SEATNO) {
                  // 设置颜色:底部和边框
                  var fillColor = "";

                  if (imageInfo.STATUS === "23") {
                    fillColor = imageInfo.bodyColor;
                  } else if (seat.WARNFLAG === "2") {
                    fillColor = imageInfo.warningColor;
                  } else {
                    fillColor = imageInfo.bodyColor;
                  }

                  seatGroup.item(0).set({ fill: fillColor });
                  //工号
                  var old_text = seatGroup.item(1).text;
                  var new_text =
                    imageInfo.STATUS === "23" ? seat.SEATNO : seat.AGENTID;

                  if (old_text === new_text && index === 1) {
                    new_text += "  ";
                  }
                  seatGroup.item(1).set({
                    text: new_text,
                    fill: "white"
                  });
                  var textNo =
                    imageInfo.STATUS === "23" ? seat.SEATNO : seat.AGENTID;
                  //登录者姓名
                  seatGroup.item(2).set({
                    text:
                      imageInfo.STATUS === "23"
                        ? imageInfo.statusName
                        : seat.AGENTNAME,
                    fill: "white"
                  });

                  var textName =
                    imageInfo.STATUS === "23"
                      ? imageInfo.statusName
                      : seat.AGENTNAME;

                  // 更换状态图
                  seatGroup.item(3).setSrc(imageInfo.iconUrl, result => {
                 
                    console.log(
                      "seat.SEATNO,",
                      seat.SEATNO,
                      ",URL,",
                      imageInfo.iconUrl,
                      ",textNo,",
                      textNo,
                      ",textName,",
                      textName
                    );
                    console.log(
                      "seat.STATUS,",
                      seat.STATUS,
                      ",本地STATUS,",
                      imageInfo.STATUS
                    );
                    count++;
                    
                    console.log("count:",count);

                    if (count === self.statusGroup.size() - 1) {
                      console.log("进入了rander,count=", count);

                      self.canvasObj.renderAll();
                      self.btnFlag = true;

                      var renderTimeafter = new Date().getTime();
                      // console.log("渲染结束时刻，", renderTimeafter);
                      console.log(
                        "反映-渲染结束的时间间隔，",
                        renderTimeafter - resTimeafter
                      );
                    }
                    
                  });
                }

              });//
            });
            //  处理预警信息
            this.tableData = response.RSP_BODY.struct1 || [];
            var struct1InfoNum = response.RSP_BODY.struct1.length
              ? response.RSP_BODY.struct1.length
              : 0;

            this.tableLabel = "坐席预警信息：" + struct1InfoNum + "条";
            // console.log(this.tableData);
            // 处理职场统计
            this.workPlaceStatistics.WaitForNextCall =
              response.RSP_BODY.WaitForNextCall;
            this.workPlaceStatistics.CallRinging =
              response.RSP_BODY.CallRinging;
            this.workPlaceStatistics.NotReadyForNextCall =
              response.RSP_BODY.NotReadyForNextCall;
            this.workPlaceStatistics.AfterCallWork =
              response.RSP_BODY.AfterCallWork;
            this.workPlaceStatistics.CallOnHold = response.RSP_BODY.CallOnHold;
            this.workPlaceStatistics.CallUnknown =
              response.RSP_BODY.CallUnknown;
            this.workPlaceStatistics.CallConsult =
              response.RSP_BODY.CallConsult;
            this.workPlaceStatistics.CallInternal =
              response.RSP_BODY.CallInternal;
            this.workPlaceStatistics.CallOutbound =
              response.RSP_BODY.CallOutbound;
            this.workPlaceStatistics.CallInbound =
              response.RSP_BODY.CallInbound;
            this.workPlaceStatistics.LoggedOut = response.RSP_BODY.LoggedOut;
          } else {
            this.$message({
              type: "error",
              message:
                response.SYS_HEAD.ReturnMessage +
                "。坐席地图查询：区域" +
                this.AREANO
            });
            // this.tableData = [];
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        });
    },
    canvasInit(num) {
      //初始化操作
      let _this = this;
      this.btnFlag = false;
      //本地 区域信息的索引num,
      num = num ? num : 0;
      // console.log("canvas初始化操作:canvasInit");
      console.log("本地areaInfo,", num, areaInfo[num]);
      this.AREANO = areaInfo[num].AREANO;
      this.backgroundURL = areaInfo[num].backgroundURL;
      this.innitInfoData = areaInfo[num].innitInfoData;
      // console.log("AREANO,", this.AREANO);
      var canvas = null;
      if (this.canvasObj.clear) {
        canvas = this.canvasObj;
        canvas.clear();
      } else {
        canvas = this.canvasObj = new fabric.Canvas("canvas");
      }
      canvas.interactive = false;
      fabric.Image.fromURL(this.backgroundURL, function(oImg) {
        var group = new fabric.Group([oImg], {
          lockScalingX: true,
          lockScalingY: true
        });
        var Img = oImg.set({
          width: 1500,
          height: 800
        });

        _this.createSeat(group);
      });
    },

    createSeat(group) {
      // 初始化工位数据
      var seatWidth = 50;
      var seatHeight = 50;
      var fontSize = 8;
      var _this = this;
      this.innitInfoData.forEach(function(seat, index) {
        fabric.Image.fromURL(statusList[0].manUrl, function(statusImg) {
          statusImg = statusImg.scale(0.6).set({
            left: seat.left + 14,
            top: seat.top + 2
          });

          //绘制矩形
          var body = new fabric.Rect({
            width: seatWidth,
            height: seatHeight,
            left: seat.left,
            top: seat.top,
            fill: "gray",
            rx: 10,
            ry: 10
          });

          // 工号seat.SEATNO
          var SEATNO = new fabric.Text(seat.SEATNO, {
            fontSize: 6,
            fill: "white",
            originX: "center",
            originY: "center",
            top: seat.top + 31,
            left: seat.left + 20
          });
          // 状态名称
          var statusName = new fabric.Text(statusList[0].statusName, {
            fontSize: fontSize,
            fill: "white",
            originX: "center",
            originY: "center",
            top: seat.top + 43,
            left: seat.left + 20
          });

          // 组合图片，
          var seatGroup = new fabric.Group(
            // [body, statusImg],
            [body, SEATNO, statusName, statusImg],
            {
              // 给每个seatGroup对应唯一的SEATNO 存位置信息;
              SEATNO: seat.SEATNO,
              // 锁住X,Y方向，不可缩放
              lockScalingX: true,
              lockScalingY: true
            }
          );
          group.addWithUpdate(seatGroup);
          if (index === _this.innitInfoData.length - 1) {
            _this.canvasObj.add(group);
            group.on("mouseup", _this.mouseScaledEventHandler);
            _this.statusGroup = group;
            //  有异步，必须在次此处加载，_this.statusGroup.forEachObject 存在时；
            _this.statusChange2();

            //  在次数开启定时任务，创建前先清除定时器，

            clearInterval(_this.timer);
            // console.log("clearInterval后，this.timer,", _this.timer);
            var setNum = 0;
            var setTimeBefore = new Date().getTime();

            _this.timer = setInterval(() => {
              console.log("定时器内部！this.timer,", _this.timer);
              var setTimerAfter = new Date().getTime();
              setNum++;
              console.log(
                "定时器间隔（毫秒），",
                (setTimerAfter - setTimeBefore) / setNum
              );

              _this.statusChange2();
            }, 40000);

            // 路由跳转时，结束定时任务；
            _this.$once("hook:beforeDestroy", () => {
              console.log("hook,", _this.timer);
              clearInterval(_this.timer);
            });
          }
        });
        // })
      });
    },
    mouseScaledEventHandler(options) {
      // console.log(options);
      // console.log(
      //   "group在canvas的当前位置- options.target.left和top：" +
      //     options.target.left +
      //     ", " +
      //     options.target.top
      // );
      // console.log(
      //   "鼠标点击在canvas的位置：" +
      //     options.absolutePointer.x +
      //     ", " +
      //     options.absolutePointer.y
      // );
      var cleft = options.target.left;
      var ctop = options.target.top;
      var mouseArray = this.innitInfoData.filter(function(ele, index, self) {
        return (
          ele.left <= options.absolutePointer.x - cleft &&
          options.absolutePointer.x - cleft <= ele.left + 50 &&
          ele.top <= options.absolutePointer.y - ctop &&
          options.absolutePointer.y - ctop <= ele.top + 50
        );
      });
      console.log(mouseArray);
      if (mouseArray.length) {
        var seatNo = mouseArray[0].SEATNO;
        console.log("mouseArray[0],", mouseArray[0],"seatNo,",seatNo);
        // console.log(seatNo);

        if (seatNo) {
          this.queryOneSeat(seatNo);
        }
      }
    },
    queryOneSeat(seatNo) {
      let self = this;
      console.log(seatNo);
      let resBody = new seatStatus();
      resBody.data.seatno = seatNo;
      console.log("queryOneSeat",this.AREANO);
       resBody.data.AREANO = this.AREANO;

      console.log("个人信息请求的resBody.data是,", resBody.data);
      requestYg(resBody)
        .then(response => {
          // console.log("后端返回的结果response,", response);
          if (response.SYS_HEAD.ReturnCode === "000000") {
            var resultData = response.RSP_BODY.AgentList;
            console.log("后端返回的结果：", resultData);
            self.currentRow[0] = resultData[0];
            // 打开弹窗
            self.dialogOptions.currentRow = self.currentRow[0];
            self.dialogOptions.title = "员工信息";
            self.dialogOptions.isShow = true;
          } else {
            this.$message({
              type: "error",
              message: response.SYS_HEAD.ReturnMessage + "。坐席工号：" + seatNo
            });
          }
          this.loading = false;
        })
        .catch(error => {
          this.loading = false;
        });
    }
  }
};
</script>


<style lang="scss" scoped>
* {
  list-style-type: none;
}
li {
  font-size: 1px;
  color: #f5f5f5;
}
.monitor {
  width: 100%;
  height: 35px;
  line-height: 33px;
  background-color: #f5f5f5;
  border-top: 1px solid #e5e5e5;
  border-bottom: 1px solid #e5e5e5;
  color: #208cf0;
  padding: 0px 35px;
  text-align: center;
}
.physical_title {
  color: #208cf0;
  padding: 0;
  margin: 0;
  // border-bottom: 1px solid #e5e5e5;
  line-height: 30px;
  margin-bottom: 5px;
}
.search_right {
  margin-left: 5px;
}
.physical_left {
  position: relative;
  // background-color:rgba(255,255,255);
  height: 100%;
  width: 1095px;
}
.mapMainBorder {
  border: 1px solid red;
  background-color: #f0f0f0;
  width: 1095px;
  height: 413px;
}
.mapimgLeft {
  width: 38.35%;
  height: 100%;
  float: left;
}
.mapimgRight {
  width: 61.65%;
  height: 100%;
  float: left;
}

.selectTree {
  min-width: 150px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}
.dialog-text {
  display: inline-block;
  width: 100%;
  text-align: center;
  color: red;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.el-card {
  width: 100%;
}
.el-form-item {
  margin-left: 30px;
}
.el-form-item1 {
  margin-left: 10px;
}
.box2-button {
  width: 80px;
}

.el-card {
  overflow: inherit;
}
.asideText {
  width: 100%;
  height: 35px;
  line-height: 33px;
  color: #409eff;
  text-align: center;
}
</style>